﻿using AutoMapper;
using B.MES.Customer.Domain;
using B.MES.Customer.Domain.DTO;
using B.MES.Customer.Infrastructure.IRepository;
using Newtonsoft.Json;
using SqlSugar;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Security.Cryptography;
using System.Text;
using System.Threading.Tasks;

namespace B.MES.Customer.Infrastructure.Repository
{
    /// <summary>
    /// 入库仓储实现层
    /// </summary>
    public class StorageRepository : BaseRepository<StockIn>, IStorageRepository
    {
        private readonly ISqlSugarClient _db;
        private readonly IMapper mapper;
        public StorageRepository(ISqlSugarClient db, IMapper mapper) : base(db)
        {
            _db = db;
            this.mapper = mapper;
        }

        /// <summary>
        /// 入库添加
        /// </summary>
        /// <param name="stockIn"></param>
        /// <returns></returns>
        public APIResult<StockInDTO> AddStockIn(StockInDTO stockIn)
        {
            APIResult<StockInDTO> result = new APIResult<StockInDTO>();

            try
            {
                // 将仓库名称列表连接成一个字符串，以逗号隔开
                // string warehouseNames = string.Join(",", stockIn.WarehouseName);

                //string deserializedStockIn = JsonConvert.SerializeObject(warehouseNames);

                // 添加入库记录，并将级联的仓库名称存储到数据库
                StockIn entity = new StockIn
                {
                    StockInType = stockIn.StockInType,
                    StockInCode = stockIn.StockInCode,
                    StockInSubject = stockIn.StockInSubject,
                    StockInDate = stockIn.StockInDate,
                    ProductionOrderID = stockIn.ProductionOrderID,
                    StockInEmployee = stockIn.StockInEmployee,
                    WarehouseName = stockIn.WarehouseName,
                    Remarks = stockIn.Remarks
                };

                var id = _db.Insertable(entity).ExecuteReturnIdentity();

                if (id > 0)
                {
                    result.Success();
                }
                else
                {
                    result.Message = "添加失败";
                }
            }
            catch (Exception ex)
            {
                result.Message = "入库添加出现异常：" + ex.Message;
            }

            return result;
        }

        /// <summary>
        /// 显示全部仓库
        /// </summary>
        /// <param name="userId"></param> 
        /// <returns></returns>
        public List<WarehouseMemuItem> GetMemus()
        {
            var warehouseList = _db.Queryable<Warehouse>().ToList();
            return GetMemu(warehouseList, 0);
        }

        /// <summary>
        /// 递归仓库
        /// </summary>
        /// <param name="list"></param>
        /// <param name="pId"></param>
        /// <returns></returns>
        private List<WarehouseMemuItem> GetMemu(IEnumerable<Warehouse> list, int pId)
        {
            try
            {
                return list.Where(x => x.Pid == pId).Select(x => new WarehouseMemuItem
                {

                    WarehouseId = x.WarehouseName.ToString(),
                    WarehouseName = x.WarehouseName,
                    children = GetMemu(list, x.WarehouseId)/*.Count > 0 ? GetMemu(list, x.Pid) : null*/
                }).ToList();
            }
            catch (Exception)
            {

                throw;
            }
        }

        /// <summary>
        /// 入库显示+分页+查询
        /// </summary>
        /// <param name="productionOrderID"></param>
        /// <param name="stockInSubject"></param>
        /// <param name="stockInDate"></param>
        /// <returns></returns>
        public PageApiResut<StockIn> GetStockInPage(string? productionOrderID, string? stockInSubject, int page, int size)
        {
            try
            {
                PageApiResut<StockIn> pageApiResut = new PageApiResut<StockIn>();

                var count = _db.Queryable<StockIn>().Count();

                var stockInList = _db.Queryable<StockIn>()
                    .WhereIF(!string.IsNullOrEmpty(productionOrderID), x => x.ProductionOrderID.Contains(productionOrderID))
                    .WhereIF(!string.IsNullOrEmpty(stockInSubject), x => x.StockInSubject.Contains(stockInSubject))
                    .ToPageList(page, size).OrderByDescending(x => x.StockInId).ToList();

                pageApiResut.TotalCount = count;
                pageApiResut.Data = stockInList;
                return pageApiResut;
            }
            catch (Exception)
            {

                throw;
            }
        }

        /// <summary>
        /// 删除入库信息
        /// </summary>
        /// <param name="stockInId"></param>
        /// <returns></returns>
        public APIResult<StockIn> DeleteData(int stockInId)
        {
            APIResult<StockIn> result = new APIResult<StockIn>();

            try
            {
                // 使用 SqlSugarClient 的 Delete 方法删除数据
                var deleteResult = _db.Deleteable<StockIn>().Where(it => it.StockInId == stockInId).ExecuteCommand();

                if (deleteResult > 0)
                {
                    result.Code = 200;
                    result.Message = "删除成功";
                }
                else
                {
                    result.Code = 0;
                    result.Message = "删除失败，未找到匹配的数据";
                }
            }
            catch (Exception ex)
            {
                result.Message = "删除数据时发生异常：" + ex.Message;
            }

            return result;
        }

        /// <summary>
        /// 入库反填
        /// </summary>
        /// <param name="stockInId"></param>
        /// <returns></returns>
       public APIResult<StockInSelDTO> GetStockInSel(int stockInId)
       {
            APIResult<StockInSelDTO> apiResult = new APIResult<StockInSelDTO>();
            try
            {
                // 根据userId查询数据库中的User对象
                StockIn stockIn = _db.Queryable<StockIn>().InSingle(stockInId);

                if (stockIn != null)
                {
                    // 将查询到的User对象映射为RequestUserDTO对象
                    StockInSelDTO requestUserDTO = mapper.Map<StockInSelDTO>(stockIn);


                    // 查询用户拥有的角色
                    List<StockIn> stockIns = _db.Queryable<StockIn>().Where(x => x.StockInId == stockInId).ToList();

                    //// 设置复选框状态，假设复选框状态通过ids字段表示
                    //requestUserDTO.ids = !string.IsNullOrEmpty(requestUserDTO.ids) ? requestUserDTO.ids : ""; // 如果复选框选中，设置为相应的值；未选中则设置为空

                    return new APIResult<StockInSelDTO>
                    {
                        Code = 200,
                        Data = requestUserDTO,
                        Message = "反填成功",
                    };
                }
                else
                {
                    return new APIResult<StockInSelDTO>
                    {
                        Code = 400,
                        Data = null, // 或者其他处理方式，视情况而定
                        Message = "反填失败"
                    };
                }
            }
            catch (Exception ex)
            {
                // 异常处理逻辑
                throw new Exception("查询入库失败", ex);
            }
       }

        /// <summary>
        /// 入库修改
        /// </summary>
        /// <param name="stockInSel"></param>
        /// <returns></returns>
        public APIResult<StockInSelDTO> UpdateStockInSel(StockInSelDTO stockInSel)
        {
            APIResult<StockInSelDTO> apiResult = new APIResult<StockInSelDTO>();

            try
            {
                // 查询要修改的用户数据
                var stockInToUpdate = _db.Queryable<StockIn>().First(x => x.StockInId == stockInSel.StockInId);

                if (stockInToUpdate != null)
                {
                    // 更新用户信息
                    stockInToUpdate.StockInType = stockInSel.StockInType;
                    stockInToUpdate.StockInCode = stockInSel.StockInCode;
                    stockInToUpdate.StockInSubject = stockInSel.StockInSubject;
                    stockInToUpdate.StockInDate = stockInSel.StockInDate;
                    stockInToUpdate.ProductionOrderID = stockInSel.ProductionOrderID;
                    stockInToUpdate.StockInEmployee = stockInSel.StockInEmployee;
                    stockInToUpdate.WarehouseName = stockInSel.WarehouseName;
                    stockInToUpdate.Remarks = stockInSel.Remarks;

                    // 使用 SqlSugar 的 Updateable 方法更新用户对象
                    _db.Updateable(stockInToUpdate).ExecuteCommand();

                    return new APIResult<StockInSelDTO>
                    {
                        Code = 200,
                        Data = stockInSel,
                        Message = "修改成功",
                        ids = _db.Updateable(stockInToUpdate).ExecuteCommand(),
                    };
                }
                else
                {
                    apiResult.Code = 404; // 用户不存在
                    apiResult.Message = "入库信息不存在，无法更新";
                }

                return apiResult;
            }
            catch (Exception ex)
            {
                apiResult.Code = 500; // 服务器内部错误
                apiResult.Message = "更新入库出错：" + ex.Message;
                return apiResult;
            }
        }
    }
}
